package com.hainatong.mvvmbase.http.interceptor;


import okhttp3.*;
import okio.Buffer;
import okio.BufferedSource;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

/**
 * 拦截器
 */
public class ResponseInterceptor implements Interceptor
{
    private static final String TAG = "ResponseInterceptor";

    private final Charset UTF8 = Charset.forName("UTF-8");

    @Override
    public Response intercept(Interceptor.Chain chain)
        throws IOException
    {
        Request request = chain.request();

        Response response = chain.proceed(request);

        ResponseBody responseBody = response.body();

        if (response.code() != 200)
        {
            // 处理 token 失效 跳转 登录页面
            if (response.code() == 401)
            {
                // 请求 401 时 直接跳转登录
                /*
                EventBus.getDefault().post(new LoginEvent());
                throw new ApiException(401, "登录验证已过期，请重新登录!");
                */
            }

            return response;
        }
        long contentLength = responseBody.contentLength();

        if (!bodyEncoded(response.headers()))
        {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null)
            {
                try
                {
                    charset = contentType.charset(UTF8);
                }
                catch (UnsupportedCharsetException e)
                {
                    return response;
                }
            }
            /*
             * if (contentLength != 0) { String result = buffer.clone().readString(charset);
             * //LogUtil.d(TAG, " response.url():" + response.request().url()); //LogUtil.d(TAG,
             * " response.body():" + result); }
             */
        }

        return response;
    }

    private boolean bodyEncoded(Headers headers)
    {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
    }

}
